package com.example.demo.config;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional
    public void run(String... args) throws Exception {
        try {
            // 尝试删除旧的外键约束
            jdbcTemplate.execute("ALTER TABLE web_links DROP FOREIGN KEY FKgwmp4ieh7qmeaqlowkx4d6c6i");
            System.out.println("成功删除旧的外键约束！");
        } catch (Exception e) {
            System.out.println("删除外键约束时出错（可能不存在）: " + e.getMessage());
        }

        try {
            // 清除错误的外键关系
            jdbcTemplate.execute("UPDATE web_links SET category_id = NULL WHERE category_id IS NOT NULL");
            System.out.println("成功清除错误的外键关系！");
        } catch (Exception e) {
            System.out.println("清除外键关系时出错: " + e.getMessage());
        }

        try {
            // 添加新的外键约束
            jdbcTemplate.execute("ALTER TABLE web_links ADD CONSTRAINT FK_weblink_link_category " +
                    "FOREIGN KEY (category_id) REFERENCES link_categories(id)");
            System.out.println("成功添加新的外键约束！");
        } catch (Exception e) {
            System.out.println("添加新外键约束时出错: " + e.getMessage());
        }
    }
} 